package com.frank.jpaSpecification.service;

import com.frank.jpaSpecification.entity.PageStudentRequest;
import com.frank.jpaSpecification.entity.Student1;
import com.frank.jpaSpecification.repository.StudentRepository;
import com.frank.jpaSpecification.specification.StudentSpecification;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import java.security.SecureRandom;
import java.util.List;
import java.util.Optional;
import java.util.Random;
import java.util.concurrent.*;

/**
 * @author 小石潭记
 * @date 2020/12/12 14:22
 * @Description: ${todo}
 */
@Service
@Slf4j
public class StudentService {

    @Autowired
    private ThreadPoolTaskExecutor asyncServiceExecutor;

    @Autowired
    private StudentRepository studentRepository;

    @Autowired
    private StudentSpecification studentSpecification;

    @Autowired
    private Schedule1Service schedule1Service;

    public Page<Student1> getStudentList(PageStudentRequest studentRequest) {
        PageRequest pageRequest = PageRequest.of(studentRequest.getPageNumber(), studentRequest.getPageSize());
        return studentRepository.findAll(studentSpecification.getStudentSpecification(studentRequest), pageRequest);
    }

    public void handleStudents(List<Student1> studentList) {
        Student1 save = save();
//        update();
        BlockingQueue<Runnable> taskQueue = new LinkedBlockingQueue<>(100);
        ExecutorService service = new ThreadPoolExecutor(
                10, 20, 0L, TimeUnit.MILLISECONDS, taskQueue);
        /*for (int i = 0; i < studentList.size(); i++) {

        }*/
        // 如果等待队列满了，线程睡眠
        while (taskQueue.size() == 100) {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                log.error("进入睡眠等待队列空闲失败，取消更新风险客户任务");
                return;
            }
        }
        asyncServiceExecutor.submit(() -> schedule1Service.handle(save));
        // 任务提交完毕，关闭线程池
        service.shutdown();
        while (!service.isTerminated()) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                log.error("进入睡眠等待跑批任务执行完成失败，停止等待执行完毕");
                return;
            }
        }
        Optional<Student1> optionalStudent1 = studentRepository.findByMobile(save.getMobile());
        System.out.println(optionalStudent1.get());
    }

    private Student1 save() {
        Student1 student1 = new Student1();
        student1.setAge(1);
        student1.setName("测试1");
        student1.setMobile(getNonce_str());
        return studentRepository.save(student1);
    }

    /**
     * 生成8位随机数
     * @return
     */
    public String getNonce_str() {
        String SYMBOLS = "0123456789";
        Random RANDOM = new SecureRandom();
        char[] nonceChars = new char[8];
        for (int index = 0; index < nonceChars.length; ++index) {
            nonceChars[index] = SYMBOLS.charAt(RANDOM.nextInt(SYMBOLS.length()));
        }
        return new String(nonceChars);
    }

    /*private void update() {
        Optional<Student1> optionalStudent1 = studentRepository.findByMobile("18329983327");
        Student1 student1 = optionalStudent1.get();
        student1.setAge(student1.getAge() + 1);
        studentRepository.save(student1);
    }*/
}
